package com.ts.enterprise.common.utils;

import com.ts.enterprise.common.consts.Constant;
import com.ts.enterprise.common.query.LoginUser;
import com.ts.enterprise.exception.BusinessException;
import com.ts.enterprise.exception.ExceptionEnum;
import io.jsonwebtoken.*;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;

/**
 * @Author Administrator
 * @Date 2021/10/19 11:13
 * @Description
 */
@Slf4j
public class JwtUtil {

    public static String encode(Map<String, Object> param, String salt) {
        String key = Constant.KEY;
        if (salt != null) {
            key += salt;
        }
        JwtBuilder jwtBuilder = Jwts.builder().signWith(SignatureAlgorithm.HS256, key);
        jwtBuilder = jwtBuilder.setClaims(param);
        return jwtBuilder.compact();

    }


    public static Map<String, Object> decode(String token, String key, String salt) {
        Claims claims = null;
        if (salt != null) {
            key += salt;
        }
        claims = Jwts.parser().setSigningKey(key).parseClaimsJws(token).getBody();
        return claims;
    }

    public static LoginUser decodeToUser(String token) {
        try {
            Map<String, Object> map = decode(token, Constant.KEY, Constant.SALT_USER);
            if (null!=map && !map.isEmpty()){
                LoginUser loginUser = new LoginUser();
                loginUser.setMobile((String) map.get("mobile"));
                loginUser.setId(Integer.parseInt(map.get("id").toString()));
                loginUser.setPlatform((String) map.get("platform"));
                loginUser.setUuid((String) map.get("uuid"));
                loginUser.setTokenKey((String) map.get("tokenKey"));
                return loginUser;
            }
        }catch (Exception ignore){}
        throw new BusinessException(ExceptionEnum.TOKEN_ANALYSIS_LOGIN_USER_EXCEPTION);

    }

    public static LoginUser decodeToBasicUser(String token) {
        try {
            Map<String, Object> map = decode(token, Constant.KEY, Constant.SALT_BASIC_USER);
            if (null != map && !map.isEmpty()) {
                LoginUser loginUser = new LoginUser();
                loginUser.setTokenType((String) map.get("tokenType"));
                loginUser.setMobile((String) map.get("mobile"));
                loginUser.setId(Integer.parseInt(map.get("id").toString()));
                loginUser.setNickname((String) map.get("nickname"));
                loginUser.setPlatform((String) map.get("platform"));
                loginUser.setUuid((String) map.get("uuid"));
                loginUser.setTokenKey((String) map.get("tokenKey"));
                return loginUser;
            }
        } catch (Exception ignore) {}
        throw new BusinessException(ExceptionEnum.TOKEN_ANALYSIS_LOGIN_USER_EXCEPTION);
    }
}
